package com.gy.smartmanagement.login.mvp;
import com.gy.smartmanagement.base.api.bean.ErrorResultBean;
import com.gy.smartmanagement.base.api.rx.SchedulersCompat;
import com.gy.smartmanagement.base.mvp.HttpDelegate;
import com.gy.smartmanagement.login.api.LoginApiService;
import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;


public class LoginPresenter extends HttpDelegate implements LoginContract.Presenter {

  private LoginContract.IView iView;
  private LoginApiService loginApiService;

  @Inject
  public LoginPresenter(LoginContract.IView iView, LoginApiService loginApiService) {
    this.iView = iView;
    this.loginApiService = loginApiService;
  }

  //修饰方法自动执行
  @Inject
  public void setUpPresenter() {
    iView.setPresenter(this);
  }

  @Override
  public void login(RequestBody loginBody) {
    Disposable disposable = loginApiService.getLoginInfo(loginBody)
        .compose(SchedulersCompat.applyIoSchedulers())  //以第一个订阅的线程为准
        .doOnSubscribe(new Consumer<Object>() {
          @Override
          public void accept(Object o) throws Exception {
            iView.show();
          }
        })
        .subscribeOn(AndroidSchedulers.mainThread())
        .doOnTerminate(new Action() {
          @Override
          public void run() throws Exception {
            iView.hide();
          }
        })
        .subscribe(new Consumer<Object>() {
          @Override
          public void accept(Object o) throws Exception {
            LoginBean loginBean = (LoginBean) o;
            iView.loginSuccess(loginBean);
          }
        }, new ErrorResultBean() {
          @Override
          protected void onError(ErrorResultBean.ErrorBean errorBean) {
            iView.onLoadFail(errorBean);
          }
        });
    addSubscription(disposable);
  }

  @Override
  public void unBindPresent() {
    onUnSubscribe();
  }

}
